# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/7/19 2:06 下午
# @Author  : 白辉东
# @Mail    : masterbai2018@outlook.com
# @File    : nlu_test.py
# @Software: PyCharm

import requests
import json
import pandas as pd

url = 'https://api.ximalaya.com/smart-os-nlu/screen-nlu/list'
route_url = 'http://api.pre.xiaoyastar.com/smart-os-nlu-pre/route'
headers = {'Content-Type': 'application/json'}


def get_route_next(intention):
    re_data = {'nluResponse': {'app': {'id': '1477', 'name': 'os.client.000001_1477'},
                               'domain': {'id': '2992', 'name': 'habit_formation'},
                               'domainType': 'RULE_DOMAIN',
                               'intention': intention,
                               'source': 'SYSTEM'
                               },
               'extraSignals': [intention['name']]}

    re = requests.post(url=route_url, headers=headers, data=json.dumps(re_data))
    repos = re.json()
    return repos


# 请求参数封装
def request_data(text, intention, tmp_next):
    app = {'id': '1477', 'name': 'os.client.000001_1477'}
    domain = {'id': '2992', 'name': 'habit_formation'}

    history_response = {'app': app,
                        'domain': domain,
                        'domainType': 'RULE_DOMAIN',
                        'intention': intention,
                        'source': 'SYSTEM',
                        'next': tmp_next}

    data_dict = {'sessionId': 'cd3b285b98334c51913171bb6844f53e',
                 'uid': 5,
                 'question': text,
                 'app': app,
                 'needMulti': 'false',
                 'historyResponse': [history_response]}

    return json.dumps(data_dict)


if __name__ == '__main__':
    data = pd.read_excel('./habit_list.xls', index_col=False, sheet_name='Sheet1', keep_default_na=False)
    for i in range(0, len(data)):
        habit_name, TTS, tmp_intention, tmp_intention_positive, answer, _ = data.iloc[i]
        tmp_data = eval(tmp_intention_positive)
        answer_list = answer.split(',')
        repos = get_route_next(eval(tmp_intention))
        new_intention = repos['intention']
        next_data = repos['next']
        # print(next_data)

        for tmp in answer_list:
            body = request_data(tmp, new_intention, next_data)
            re = requests.post(url=url, headers=headers, data=body)
            response_data = re.json()[0]

            name = response_data['intention']['name']
            print('*' * 100)
            print(f'问答语句：{TTS}')
            print(f'habit_name: {habit_name}, intention: {tmp_intention}, intention_positive: {tmp_intention_positive}, answer: {tmp}')
            print(name)

            # if name == 'habit_formation_negative':
            #     print('*' * 100)
            #     print(f'问答语句：{TTS}')
            #     print(f'habit_name: {habit_name}, intention: {tmp_intention}, intention_positive: {tmp_intention_positive}, answer: {tmp}')
            #     print(name)
